package com.columboid.web.servlets;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import com.columboid.protocol.syncml.helper.JaxbHelper;
import com.columboid.protocol.syncml.representation.Chal;
import com.columboid.protocol.syncml.representation.Status;
import com.columboid.protocol.syncml.representation.SyncBody;
import com.columboid.protocol.syncml.representation.SyncHdr;
import com.columboid.protocol.syncml.representation.SyncML;

/**
 * Servlet implementation class ChallengeServlet
 */
public final class ChallengeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChallengeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// generate a nonce
		String nonce = generateNonce();

		// send it back to the client
		sendBackNonce(request, response, nonce);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// generate a nonce
		String nonce = generateNonce();

		// send it back to the client
		sendBackNonce(request, response, nonce);
	}

	private String generateNonce() {
		String nonce = UUID.randomUUID().toString();
		return nonce;
	}

	private void sendBackNonce(HttpServletRequest request,
			HttpServletResponse response, String nonce) throws IOException {
		String sml = createSyncMLMessage(nonce);
		response.getWriter().write(sml);
	}

	private String createSyncMLMessage(String nonce) {
		SyncML sml = new SyncML();

		sml.setSyncHdr(new SyncHdr() {
			{
				setVerDTD("1.1");
				setSessionID("1");

			}
		});

		sml.setSyncBody(new SyncBody() {
			{
				getKeyOrRoutingOrAlert().add(new Status() {
					{
						setChal(new Chal() {
							{
								String meta = "<Type xmlns='syncml:metinf'>auth-md5</Type><Format xmlns='syncml:metinf'>b64</Format>";
								setMeta(meta);
							}
						});

						setData("some data");
					}
				});

			}
		});	
		
		
		try {
			return JaxbHelper.getJaxbObjectString(sml,false);
		} catch (JAXBException e) {
			return "";
		}

	}

}
